import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, notification, Cascader } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { DICT } from '../enum';
import { getBuildFn } from '@/utils/get_position';
import styles from '@/styled/form.less';
import { SearchCol, SearchRow } from '@/styled/form';
import { DividerItem } from '@/components/DividerItem';

interface Props extends FormComponentProps {
  dispatch?: Function;
  data?: {
    id: number;
    brandId?: any;
    productId?: any;
    buildId?: any;
    floorId?: any;
    areaId?: any;
    floorPlanX?: any;
    floorPlanY?: any;
    installationTime?: any;
    overdueTime?: any;
    installLocationName?: string;
    buildName?: string;
    floorName?: string;
    areaName?: string;
    fireDeviceType?: number;
    fireDeviceTypeName?: string;
  };
  keys?: Array<string>;
  sub?: Array<any>;
  locationData?: Array<any>;
  optionData?: Array<any>;
  areaData?: Array<any>;
  brandData?: Array<string>;
  productData?: Array<string>;
  dict?: object;
  cond?: any;
  typeData?: Array<any>;
  typeOptionData?: object;
}

@connect(({ archives_point }) => ({
  locationData: archives_point.locationData || [],
  optionData: archives_point.optionData || {},
  areaData: archives_point.areaData || {},
  cond: archives_point.cond || {},
  dict: archives_point.dict || {},
  typeData: archives_point.typeData || {},
  typeOptionData: archives_point.typeOption || {},
}))
class FormItem extends Component<Props, any> {
  state = {
    multiple: 1,
    pos_input: null,
    isChange: true,
    installLocationList: [],
    buildId: '',
    floorId: '',
    areaId: '',
    installLocationName: '',
    productId: '',
    brandList: '',
    option: [],
    areaName: '',
    typeOption: [],
    typeName: '',
    buildList: [],
    isDetails: true
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;
    dispatch({
      type: 'archives_point/queryDict',
      payload: {
        keyList: DICT
      }
    });
    // 查建筑区域
    dispatch({
      type: 'archives_point/queryLocation'
    }).then(() => {
      let { locationData = [] } = this.props;
      locationData && Array.isArray(locationData) && locationData.map(item => {
        item.label = item.name;
        item.value = item.id;
        item.isLeaf = false;
        item.level = '1';
        delete item.name;
        return item;
      });
      this.setState({ option: locationData });

    });


    if (data) {
      const {
        id,
        buildId,
        floorId,
        areaId,
        buildName,
        floorName,
        areaName,
        fireDeviceTypeName,
        fireDeviceType,
        ...items
      } = data;

      const ans = {
        ...items,
        fireDeviceType: fireDeviceType ? fireDeviceType.toString() : null,
      };

      this.setState({
        buildId,
        floorId,
        areaId,
        buildList: [buildId, floorId, areaId],
        areaName: `${buildName}/${floorName}/${areaName ? areaName : ''}`,
      }, () => {
        form.setFieldsValue(ans)
      });
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form, data, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {

        const address = this.state.buildList;

        if (Array.isArray(address) && address.length > 1) {
          values.buildId = address[0];
          values.floorId = address[1];
          values.areaId = address.length > 2 ? address[2] : null;
        } else {
          notification.warn({
            message: `保存失败`,
            description: '请选择至楼层',
          });
        }
        // delete values.address;

        values.fireSystemCode = 60001;
        values.fireDeviceType = values.fireDeviceType ? values.fireDeviceType.toString() : null;
        data && data.id ? dispatch({
          type: 'archives_point/update',
          payload: {
            id: data.id,
            ...values
          }
        }) : dispatch({
          type: 'archives_point/create',
          payload: values
        })
      } else {
        notification['error']({
          message: `保存失败`,
          description: '字段验证不通过',
        });
      }
    })
  };

  onChangeCascader = (value) => {
    this.setState({
      buildList: value,
    })
  };

  loadData = (selectedOptions) => {
    const { dispatch, locationData } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const level = targetOption.level;
    targetOption.loading = true;
    getBuildFn(level, dispatch, 'archives_point/optionLocation', 'archives_point/areaLocation', targetOption, locationData, this);
  };

  loadTypeData = (selectedOptions) => {

  }

  onChangeTypeCascader = (value) => {
  }
  handleShow = (flag) => {
    this.setState({
      isDetails: flag
    })
  }
  render() {
    const { form, dict = {}, data } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 14 },
      },
    };
    const noItemLayout = {
      wrapperCol: { span: 14, offset: 8 },
    };

    const Info = DividerItem(data && data.id ? 'icon-editor_' : 'icon-editor_', '基础信息')
    const DetailsOpen = DividerItem('icon-management', '详细资料', true, this.state.isDetails, this.handleShow)
    return (
      <Form onSubmit={this.handleSubmit}>
        <Info />
        <SearchRow>
          <SearchCol key={0} span={12}>
            <Form.Item
              {...formItemLayout}
              label='消防重点部位名称'
            >
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '消防重点部位名称' }],
              })(
                <Input placeholder='请输入' />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol key={1} span={12}>
            <Form.Item
              {...formItemLayout}
              label='所在位置'
              className={styles.fileRequire}
            >
              <Cascader
                // disabled={!!(data && data.id)}
                options={this.state.option || this.props.locationData}
                loadData={this.loadData}
                changeOnSelect
                placeholder={this.state.areaName || "请选择"}
                onChange={this.onChangeCascader}
              />
            </Form.Item>
          </SearchCol>
        </SearchRow>

        <SearchRow>
          <SearchCol key={2} span={12}>
            <Form.Item
              {...formItemLayout}
              label='重点部位类型'
            >
              {getFieldDecorator('fireDeviceType', {
                rules: [{ required: true, message: '请选择重点部位类型' }],
              })(
                DropDownSelect(dict, 'sub')
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol key={3} span={12}>
            <Form.Item
              {...noItemLayout}
            >
              {getFieldDecorator('address', {
                rules: [{ required: true, message: '请输入详细地址' }],
              })(
                <Input.TextArea rows={4} style={{ width: '100%', marginTop: '-15px' }} />
              )}
            </Form.Item>
          </SearchCol>

        </SearchRow>

        <SearchRow>
          <SearchCol key={5} span={12}>
              <Form.Item
                {...formItemLayout}
                label='责任人'
              >
                {getFieldDecorator('dutyName', {
                  rules: [{ required: true, message: '请输入责任人' }],
                })(
                  <Input placeholder='请输入' />
                )}
              </Form.Item>
            </SearchCol>
          <SearchCol key={4} span={12}>
            <Form.Item
              {...formItemLayout}
              label='使用性质'
            >
              {getFieldDecorator('flag', {
                rules: [{ required: true, message: '请输入使用性质' }],
              })(
                <Input placeholder='请输入' />
              )}
            </Form.Item>
          </SearchCol>
   
        </SearchRow>
        {/* 显示和隐藏 */}
        <DetailsOpen />
        <div style={{ display: `${this.state.isDetails ? 'block' : 'none'}` }}>
          <SearchRow>
            <SearchCol key={6} span={12}>
              <Form.Item
                {...formItemLayout}
                label='建筑耐火等级'
              >
                {getFieldDecorator('buildFireLevel', {
                  rules: [{ required: false, message: '请选择建筑耐火等级' }],
                })(
                  DropDownSelect(dict, 'build.fire.level')
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol key={7} span={12}>
              <Form.Item
                {...formItemLayout}
                label='火灾危险性'
              >
                {getFieldDecorator('fireDangerLevel', {
                  rules: [{ required: false, message: '火灾危险性' }],
                })(
                  DropDownSelect(dict, 'fire.danger.level')
                )}
              </Form.Item>
            </SearchCol>

          </SearchRow>
          <SearchRow>
            <SearchCol key={8} span={12}>
              <Form.Item
                {...formItemLayout}
                label='职工人数'
              >
                {getFieldDecorator('quantity', {
                  rules: [{ required: false, message: '职工人数' }],
                })(
                  <Input type="number" placeholder='请输入' addonAfter="人" />
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol key={9} span={12}>
              <Form.Item
                {...formItemLayout}
                label='建筑面积'
              >
                {getFieldDecorator('floorSpace', {
                  rules: [{ required: false, message: '所在位置' }],
                })(
                  <Input type="number" placeholder='请输入' addonAfter="㎡" />
                )}
              </Form.Item>
            </SearchCol>

          </SearchRow>
          <SearchRow>
            <SearchCol key={10} span={12}>
              <Form.Item
                {...formItemLayout}
                label='建筑高度'
              >
                {getFieldDecorator('height', {
                  rules: [{ required: false, message: '所在位置' }],
                })(
                  <Input type="number" placeholder='请输入' addonAfter="m" />
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol key={11} span={12}>
              <Form.Item
                {...formItemLayout}
                label='确立消防安全重点部位的原因'
              >
                {getFieldDecorator('reason', {
                  rules: [{ required: false, message: '确立消防安全重点部位的原因' }],
                })(
                  <Input.TextArea placeholder='请输入' rows={2} />
                )}
              </Form.Item>
            </SearchCol>
          </SearchRow>
          <SearchRow>
            <SearchCol key={12} span={12}>
              <Form.Item
                {...formItemLayout}
                label='防火标志的设立情况'
              >
                {getFieldDecorator('fireSignSituation', {
                  rules: [{ required: false, message: '防火标志的设立情况' }],
                })(
                  <Input placeholder='请输入' />
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol key={13} span={12}>
              <Form.Item
                {...formItemLayout}
                label='危险源情况'
              >
                {getFieldDecorator('dangerSituation', {
                  rules: [{ required: false, message: '危险源情况' }],
                })(
                  <Input placeholder='请输入' />
                )}
              </Form.Item>
            </SearchCol>
          </SearchRow>

          <SearchRow>
            <SearchCol key={14} span={12}>
              <Form.Item
                {...formItemLayout}
                label='火种情况'
              >
                {getFieldDecorator('fireSituation', {
                  rules: [{ required: false, message: '火种情况' }],
                })(
                  <Input placeholder='请输入' />
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol key={15} span={12}>
              <Form.Item
                {...formItemLayout}
                label='消防安全管理措施'
              >
                {getFieldDecorator('remark', {
                  rules: [{ required: false, message: '消防安全管理措施' }],
                })(
                  <Input.TextArea placeholder='请输入' rows={4} />
                )}
              </Form.Item>
            </SearchCol>
          </SearchRow>
        </div>

        <div style={{ display: 'flex', position: 'fixed', bottom: '50px', left: '271px' }}>
          <Button style={{ marginTop: '3%', marginLeft: '5%' }} onClick={() => window.history.back()}>取消</Button>
          <Button style={{ marginTop: '3%', marginLeft: '25%' }} type="primary" htmlType="submit">保存</Button>
        </div>
      </Form>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;
